package com.leo.blog.login.web;

import com.leo.blog.login.config.Inner;
import com.leo.blog.util.ImageCodeUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @Classname ImageController
 * @Description TODO
 * @Date 2023/4/13 10:04
 * @Created by XiongXiong
 * @Author: X.I.O
 */
@RestController
@RequestMapping("image")
public class ImageController {

    @Inner
    @GetMapping("/getImage")
    public void ImageController(HttpServletResponse response,
                                @RequestParam("sessionId")String sessionId) throws IOException {

        byte[] captchaOutputStream = null;
        ByteArrayOutputStream imgOutputStream = null;
        ServletOutputStream responseOutputStream=null;
        try {
            imgOutputStream=new ByteArrayOutputStream();
            BufferedImage bufferedImage= ImageCodeUtils.getImage(sessionId);
            response.setHeader("Cache-Control", "no-store");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/jpeg");

            ImageIO.write(bufferedImage, "jpg", imgOutputStream);
            responseOutputStream = response.getOutputStream();

            captchaOutputStream = imgOutputStream.toByteArray();
            responseOutputStream.write(captchaOutputStream);
            responseOutputStream.flush();

        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(responseOutputStream!=null){
                    responseOutputStream.close();
                }
            }catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
